package other.thread;

import java.util.concurrent.atomic.AtomicInteger;

public class PrintAB {
    public static void main(String[] args) {
        AtomicInteger state = new AtomicInteger(1);
        Object resource = new Object();
        new Thread(new ThreadA(state, resource)).start();
        new Thread(new ThreadB(state, resource)).start();
    }

}

class ThreadA implements Runnable {

    private AtomicInteger state;

    private Object resource;

    public ThreadA(AtomicInteger state, Object resource) {
        this.state = state;
        this.resource = resource;
    }

    @Override
    public void run() {
        while (state.get() < 100) {
            synchronized (resource) {
                while (state.get() % 2 == 0) {
                    try {
                        resource.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(state);
                state.addAndGet(1);
                resource.notify();
            }
        }
    }
}

class ThreadB implements Runnable {

    private AtomicInteger state;

    private Object resource;

    public ThreadB(AtomicInteger state, Object resource) {
        this.state = state;
        this.resource = resource;
    }

    @Override
    public void run() {
        while (state.get() < 100) {
            synchronized (resource) {
                while (state.get() % 2 == 1) {
                    try {
                        resource.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(state);
                state.addAndGet(1);
                resource.notify();
            }
        }
    }
}
